package cn.anecansaitin.not_enough_harness.common.payload;

import cn.anecansaitin.not_enough_harness.NotEnoughHarness;
import cn.anecansaitin.not_enough_harness.common.ModCapabilities;
import cn.anecansaitin.not_enough_harness.common.capability.harness_capability.HarnessCapabilityHandler;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.animal.HappyGhast;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext;

public record UsingHarnessCapability() implements CustomPacketPayload {
    public static UsingHarnessCapability INSTANCE = new UsingHarnessCapability();
    public static final CustomPacketPayload.Type<UsingHarnessCapability> TYPE = new CustomPacketPayload.Type<>(ResourceLocation.fromNamespaceAndPath(NotEnoughHarness.MOD_ID, "using_harness_capability"));
    public static final StreamCodec<FriendlyByteBuf, UsingHarnessCapability> CODEC = StreamCodec.unit(new UsingHarnessCapability());

    @Override
    public Type<? extends CustomPacketPayload> type() {
        return TYPE;
    }

    public static void handler(UsingHarnessCapability payload, IPayloadContext context) {
        Player player = context.player();
        Entity vehicle = player.getVehicle();

        if (!(vehicle instanceof HappyGhast ghast)) {
            return;
        }

        ItemStack harness = ghast.getItemBySlot(EquipmentSlot.BODY);

        if (harness.isEmpty()) {
            return;
        }

        HarnessCapabilityHandler cap = harness.getCapability(ModCapabilities.HARNESS_CAPABILITY_HANDLER);

        if (cap == null) {
            return;
        }

        cap.use(harness, ghast, player);
    }
}
